<?php

namespace app\award;

use app\models\order\Order;
use app\models\order\OrderItem;
use app\models\product\ProductArea;
use app\models\SetUserUp;
use app\models\user\User;
use app\models\user\UserAccount;
use app\models\user\UserCommission;
use app\models\user\UserLevel;
use app\services\Chain;

class Up
{
    protected $order;
    protected $user;

    protected $set;

    protected $first_order_item;

    public function __construct(Order $order)
    {
        $this->order = $order;
        $this->user = User::findOne(['id' => $this->order->user_id]);

        $first_order_item = OrderItem::find()
            ->where(['order_id' => $order->id])
            ->orderBy(['id' => SORT_ASC])
            ->limit(1)
            ->one();

        $this->first_order_item = $first_order_item;

        $product_id = $first_order_item->product_id;

        $this->set = SetUserUp::getLastOne();

        $is_bao = ProductArea::checkBao($product_id);
        $is_material = ProductArea::checkMaterial($product_id);

        // 材料区, 可以升级会员
        if ($is_material) {
            if ($this->order->total_pay > 0) {
                if ($this->user->level < UserLevel::$keys['vip1']) {
                    $this->user->level = UserLevel::$keys['vip1'];
                    $this->user->save();
                }
            }
        }

        // 必须是报单区
        if ($is_bao) {
            $this->upMyself();
        }
    }

    // 升级自己
    protected function upMyself($active = false)
    {
        $amount = $this->order->total_pay - $this->order->total_freight;

        // 总代
        if ($amount >= $this->set->svip2) {
            if ($this->user->level < UserLevel::$keys['svip2']) {
                $this->user->level = UserLevel::$keys['svip2'];
                $this->user->save();
            }
        }

        // 代理
        else if ($amount >= $this->set->svip1) {
            if ($this->user->level < UserLevel::$keys['svip1']) {
                $this->user->level = UserLevel::$keys['svip1'];
                $this->user->save();
            }
        }

        // sivp
        else if ($amount >= $this->set->vip4) {
            if ($this->user->level < UserLevel::$keys['vip4']) {
                $this->user->level = UserLevel::$keys['vip4'];
                $this->user->save();
            }
        }

        // vip
        else if ($amount >= $this->set->vip3) {
            if ($this->user->level < UserLevel::$keys['vip3']) {
                $this->user->level = UserLevel::$keys['vip3'];
                $this->user->save();
            }
        }


    }


}